package com.pandas.community.service;

import com.pandas.community.Utils.CommunityConstant;
import com.pandas.community.Utils.CommunityUtil;
import com.pandas.community.Utils.MailClient;
import com.pandas.community.Utils.RedisKeyUtil;
import com.pandas.community.dao.LoginTicketMapper;
import com.pandas.community.dao.UserMapper;
import com.pandas.community.entity.LoginTicket;
import com.pandas.community.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class UserService implements CommunityConstant {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

//    @Autowired
//    private LoginTicketMapper loginTicketMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;


    public User selectById(int id){

//        return userMapper.selectById(id);

        //先从cache中找
        User user = getCache(id);
        if(user == null){
            //找不到
            user = initCache(id);
        }

        return user;
    }

    //处理注册信息
    public Map<String, Object> register(User user){
        Map<String, Object> map = new HashMap<>();

        if(user == null) throw new IllegalArgumentException("参数不能为空！");

        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg", "用户名不能空！");
            return map;
        }
        if(StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg", "密码不能为空！");
            return map;
        }

        if(StringUtils.isBlank(user.getEmail())){
            map.put("emailMsg", "邮箱不能为空！");
            return map;
        }

        User u = userMapper.selectByName(user.getUsername());
        if(u != null){
            map.put("usernameMsg","该用户名已被注册！");
            return map;
        }

        u = userMapper.selectByEmail((user.getEmail()));
        if(u != null){
            map.put("emailMsg", "该邮箱已被注册！");
            return map;
        }

        // 注册用户
        user.setSalt(CommunityUtil.generateUUID().substring(0,5));
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        user.setStatus(0);
        user.setType(0);
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        userMapper.insertUser(user);

        //发送激活页面
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url",url);
        String content = templateEngine.process("/mail/activation", context);
        mailClient.sendMail(user.getEmail(),"账号激活",content);

        return map;

    }


    public Map<String, Object> forget(String email){
        Map<String, Object> map = new HashMap<>();
        if(email == null) throw new IllegalArgumentException("参数不能为空！");
        // TO-DO
        return map;
    }

    //查询激活状态
    public int activation(int userId, String code){
        User user = userMapper.selectById(userId);
        if(user.getStatus() == 1){
            return ACTIVATION_REPEAT;
        }else if(user.getActivationCode().equals(code)){
            userMapper.updateStatus(userId,1);
            //更新时，清除cache
            clearCache(userId);
            return ACTIVATION_SUCCESS;
        }else{
            return ACTIVATION_FAILED;
        }
    }


    //登录
    public Map<String, Object> login(String username, String password, int expiredSeconds){
        Map<String, Object> map = new HashMap<>();
        if(StringUtils.isBlank(username)){
            map.put("usernameMsg","请输入用户名！");
            return map;
        }

        if(StringUtils.isBlank(password)){
            map.put("passwordMsg","请输入密码！");
            return map;
        }

        User u = userMapper.selectByName(username);
        if(u == null){
            map.put("usernameMsg","该用户不存在！");
            return map;
        }

        password = CommunityUtil.md5(password + u.getSalt());
        if(!u.getPassword().equals(password)){
            map.put("passwordMsg","密码不正确！");
            return map;
        }

        if(u.getStatus() == 0){
            map.put("usernameMsg","该用户未激活!");
            return map;
        }

        //生成登录凭证
        LoginTicket ticket = new LoginTicket();
        ticket.setUserid(u.getId());
        ticket.setStatus(0);
        ticket.setTicket(CommunityUtil.generateUUID());
        ticket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));

//        loginTicketMapper.insertLoginTicket(ticket);

        //redis存入登录凭证
        String ticketKey = RedisKeyUtil.getLoginTicketKey(ticket.getTicket());
        redisTemplate.opsForValue().set(ticketKey, ticket);

        map.put("ticket", ticket.getTicket());
        return map;
    }

    //退出
    public void logout(String ticket){

        //redis取出
        String ticketKey = RedisKeyUtil.getLoginTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(ticketKey);
        loginTicket.setStatus(1);
        //再存入
        redisTemplate.opsForValue().set(ticketKey, loginTicket);

//        loginTicketMapper.updateStatus(ticket, 1);
        return;
    }

    //得到loginticket
    public LoginTicket getLoginTicket(String ticket){
        String ticketKey = RedisKeyUtil.getLoginTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(ticketKey);
        return loginTicket;
//        return loginTicketMapper.selectByTicket(ticket);
    }

    // 更新头像
    public int updateHeadUrl(int userid, String url){
        int rows = userMapper.updateHeader(userid, url);
        clearCache(userid);
        return rows;
    }

    public User selectByName(String username){
        return userMapper.selectByName(username);
    }

    //1.优先从redis中取
    private User getCache(int userid){
        String userKey = RedisKeyUtil.getUserKey(userid);
        return (User)redisTemplate.opsForValue().get(userKey);
    }

    //2.取不到，初始化缓存
    private User initCache(int userid){
        User user = userMapper.selectById(userid);
        String userKey = RedisKeyUtil.getUserKey(userid);
        // 3600s
        redisTemplate.opsForValue().set(userKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }


    //3.数据变更时清除缓存
    private void clearCache(int userid){
        String userKey = RedisKeyUtil.getUserKey(userid);
        redisTemplate.delete(userKey);
    }
}
